local ELEMENT_MAX_NUMBER = 3
local VALUE_MAX_LENGTH = 128

local Util = require('skywalking.util')
local encode_base64 = Util.encode_base64
local decode_base64 = Util.decode_base64

local Propagation = require('skywalking.propagation')
local Const = require('skywalking.constants')

local _M = {}

function _M.new()
    return setmetatable({ correlation = {} }, {__index = _M})
end

function _M.decode(correlation_context, carrier)
    Propagation.DecodeSW8Correlation(correlation_context, Const.HeaderKeySw8Correlation, carrier)
end

function _M.encode(correlation_context, injector)
    if not injector then
        return
    end
    Propagation.EncodeSW8Correlation(correlation_context, Const.HeaderKeySw8Correlation, injector)
end

-- Put the custom key/value into correlation context.
function _M.put(correlation_context, key, value)
    -- key must not null
    if not key then
        return
    end

    -- remove and return previous value when value is empty
    if not value or #value == 0 then
        correlation_context.correlation[key] = nil
        return
    end

    -- check value length
    if #value > VALUE_MAX_LENGTH then
        return
    end

    -- already contain key, overwrite it
    if  correlation_context.correlation[key] then
        correlation_context.correlation[key] = value
        return
    end


    -- check keys count
    local contextLength = 0
    for k,v in pairs( correlation_context.correlation) do
        contextLength = contextLength + 1
    end
    if contextLength >= ELEMENT_MAX_NUMBER then
        return
    end

    -- setting
    correlation_context.correlation[key] = value
end

return _M
